package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserServiceImpl {
    private final String url = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    public User login(UserLoginDTO dto){
        //调用微信后台服务接口，获取返回对象
        Map<String,String> object = new HashMap<>();
        object.put("appid", weChatProperties.getAppid());
        object.put("secret", weChatProperties.getSecret());
        object.put("js_code",dto.getCode());
        object.put("grant_type","authorization_code");
        String result = HttpClientUtil.doGet(url,object);
        JSONObject result_ = JSONObject.parseObject(result);
        String openid = result_.get("openid").toString();
        User newuser = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
        User user = userMapper.getByopenid(openid);
        //判断openid是否存在，如不存在，自动加入user表（注册）
        if(user == null){
            //插入user表
            userMapper.insert(newuser);
        }
        else{
            newuser.setId(user.getId());
        }
        //封装User对象，返回
        return newuser;
    }
}
